package com.nanbei.queue;

import java.util.Iterator;

/**
 * @ClassDescription: 无序数组实现优先级队列
 * @JdkVersion: 17
 * @Author: BaoShan.li
 * @Created: 2023/11/28 17:56
 */
public class DisorderQueue<E extends Priority> implements QueueInterface<E> {

    Priority[] array;
    int size;

    public DisorderQueue(int capacity) {
        this.array = new Priority[capacity];
    }

    @Override
    public boolean offer(E value) {
        if (isFull()) {
            return false;
        }
        array[size++] = value;
        return true;
    }

    /**
     * 获取优先级最大的值
     *
     * @return 返回数据
     */
    @Override
    public E poll() {
        if (isEmpty()) {
            return null;
        }
        //通过遍历数组 寻找到优先级最大的下标
        int maxIndex = getMaxIndex();
        E e = (E) array[maxIndex];
        //获取值后将该下标后的值往前挪动一位，并将最后以为数据删除
        remove(maxIndex);
        return e;
    }



    @Override
    public E peek() {
        if (isEmpty()) {
            return null;
        }
        int maxIndex = getMaxIndex();
        return (E) array[maxIndex];
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public boolean isFull() {
        return size == array.length;
    }

    public int getMaxIndex() {
        int temp = 0;
        for (int i = 1; i < size; i++) {
            if (array[temp].getPriority() < array[i].getPriority()) {
                temp = i;
            }
        }
        return temp;
    }

    private void remove(int maxIndex) {
        if (maxIndex < size-1){
            System.arraycopy(array, maxIndex + 1, array, maxIndex, size - maxIndex - 1);
        }
        array[--size] = null;
    }


}
